import { queryPermissionsByUser } from '@/api/user'
import { asyncRoutes ,constantRoutes} from '@/router'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {

  GetPermissionList({ commit }) {
    return new Promise((resolve, reject) => {
      queryPermissionsByUser().then(res => {
        const menu = res.data
        let accseeRoutes = filterAsyncRoutes(asyncRoutes, menu)
        console.log("accseeRoutes" + accseeRoutes)
        commit('SET_ROUTES', accseeRoutes)
        resolve(accseeRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  },
}
// judge ausycRoutes has permisson by  BackEnd Routes
//dynamicRoute is signle aysncRoute
//
function hasPermission(dynamicRoute, backEndRoute) {
  if(dynamicRoute.path ){
    if(backEndRoute.path === dynamicRoute.path){
      return true
    }
    else{
      return false
    }
  }
  else {
    return false
  }
}

//
export function filterAsyncRoutes(dynamicRoutes, backEndRoutes) {
  const res=[]
  backEndRoutes.forEach(
    backEndRoute=>{
      console.log(backEndRoute)
      dynamicRoutes.filter( dynamicRoute =>{
        if(hasPermission(backEndRoute,dynamicRoute)){

          if (backEndRoute.children && backEndRoute.children.length) {
            // todo problem
            dynamicRoute.children=filterAsyncRoutes(dynamicRoute.children, backEndRoute.children)
            //
          }
          res.push(dynamicRoute)
        }
      })
    }
  )
  return  res
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
